package com.lu.http

import android.content.Context
import android.util.Log
import com.squareup.moshi.Moshi
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.moshi.MoshiConverterFactory
import com.lu.http.cookie.CookieJarImp
import com.lu.http.core.HttpsFactory
import com.lu.http.interceptor.DefaultInterceptorFactory
import com.lu.http.interceptor.IInterceptorFactory
import com.lu.http.json.MapAdapter
import java.util.concurrent.TimeUnit

/**
 *author: luqihua
 *date:2021/10/19
 *description:
 **/
object HttpManager {
    private const val TIME_OUT = 10
    private lateinit var sOkHttpClient: OkHttpClient

    /**
     * 初始化  OkHttpClient.Builder
     */
    @JvmStatic
    fun init(
        context: Context,
        factory: IInterceptorFactory = DefaultInterceptorFactory()
    ) {
        val httpsFactory = HttpsFactory()
        val builder = OkHttpClient.Builder()
            .connectTimeout(TIME_OUT.toLong(), TimeUnit.SECONDS)
            .readTimeout(TIME_OUT.toLong(), TimeUnit.SECONDS)
            .cookieJar(CookieJarImp(context))
            //            .cache(OkCache(context).createCache())
            .sslSocketFactory(httpsFactory.sslSocketFactory, httpsFactory.x509TrustManager)
            .addInterceptor(loggingInterceptor())
            .hostnameVerifier { _, _ -> true }

        builder.interceptors().addAll(factory.getInterceptors())
        builder.networkInterceptors().addAll(factory.getNetworkInterceptors())
        sOkHttpClient = builder.build()
    }

    @JvmStatic
    fun init(client: OkHttpClient) {
        sOkHttpClient = client
    }

    @JvmStatic
    fun changeOkHttpClient(block: ((OkHttpClient.Builder) -> Unit)) {
        val builder = sOkHttpClient.newBuilder()
        block.invoke(builder)
        sOkHttpClient = builder.build()
    }

    /**
     * 创建一个新的Retrofit
     *
     * @param baseUrl
     * @return
     */
    @JvmStatic
    fun newRetrofit(baseUrl: String): Retrofit {
        val moshi = Moshi.Builder()
            .add(KotlinJsonAdapterFactory())
            .add(MapAdapter())
            .build()

        return Retrofit.Builder()
            .baseUrl(baseUrl)
            .client(sOkHttpClient)
            .addConverterFactory(MoshiConverterFactory.create(moshi))
            .build()
    }

    /**
     * 提供logger
     *
     * @return
     */
    private fun loggingInterceptor(): HttpLoggingInterceptor {
        return HttpLoggingInterceptor { message: String ->
            Log.d("OK-HTTP", message)
        }.setLevel(HttpLoggingInterceptor.Level.BODY)
    }
}